<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
	<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
	<title>范闲商城-商品列表</title>
	<link rel="stylesheet" type="text/css" href="../static/css/reset.css">
	<link rel="stylesheet" type="text/css" href="../static/css/main.css">
	<script type="text/javascript" src="../static/layui/layui.js"></script>
	<link rel="stylesheet" href="../static/layui/css/layui.css">
	<script type="text/javascript" src="../static/mylayer.js" charset="utf-8"></script>
	<script type="text/javascript" src="../static/js/jquery-1.12.4.min.js"></script>
	<script type="text/javascript" src="../static/js/jquery-ui.min.js"></script>
	<style>
		.avatar-img {
			width: 20px; /* 设置头像图片的宽度 */
			height: 20px; /* 设置头像图片的高度，可以根据需要调整 */
			border-radius: 50%; /* 使图片呈现圆形 */
			margin-right: 10px; /* 设置头像图片与用户名之间的间距，可以根据需要调整 */
		}
	</style>
</head>
<body>
<!--	<div class="header_con">-->
<!--		<div class="header">-->
<!--			<div class="welcome fl">欢迎来到范闲商城!</div>-->
<!--			<div class="fr" id="IFLogin">-->


<!--			</div>-->
<!--		</div>		-->
<!--	</div>-->
	<div th:replace="header::top"></div>

	<div class="search_bar clearfix">
		<a href="/" class="logo fl"><img src="../static/pic/fanxian-mall.png" width="150px" height="60px"></a>
		<div class="search_con fl">
			<input type="text" id="searchInput" class="input_text fl" placeholder="搜索商品">
			<input type="button" id="searchButton" class="input_btn fr" value="搜索">
		</div>
		<div class="guest_cart fr">
			<a href="/page/cart" id="cart" class="cart_name fl">我的购物车</a>
		</div>
	</div>

	<div class="navbar_con">
		<div class="navbar clearfix">
			<div class="subnav_con fl">
				<h1>全部商品分类</h1>	
				<span></span>			
				<ul class="subnav" id="LAY_CategoryList">
					<!--<li><a href="#" class="fruit">新鲜水果</a></li>
					<li><a href="#" class="seafood">海鲜水产</a></li>
					<li><a href="#" class="meet">猪牛羊肉</a></li>
					<li><a href="#" class="egg">禽类蛋品</a></li>
					<li><a href="#" class="vegetables">新鲜蔬菜</a></li>
					<li><a href="#" class="ice">速冻食品</a></li>-->
				</ul>
			</div>
			<ul class="navlist fl">
				<li><a href="/">首页</a></li>
				<li class="interval">|</li>
				<li><a href="/page/list">全部商品</a></li>
				<li class="interval">|</li>
				<li><a href="/page/turntable">抽奖</a></li>
			</ul>
		</div>
	</div>

	<div class="breadcrumb" id="categoryName">
		<a href="/page/list">全部分类</a>
		<span>></span>
		<a href="#">新鲜水果</a>
	</div>

	<div class="main_wrap clearfix">
		<div class="l_wrap fl clearfix">
			<div class="new_goods">
				<h3>智能推荐</h3>
				<ul id="newProduct">
					<li>
						<a href="#"><img src="../static/images/goods/goods001.jpg"></a>
						<h4><a href="#">进口柠檬</a></h4>
						<div class="prize">￥3.90</div>
					</li>
					<li>
						<a href="#"><img src="../static/images/goods/goods002.jpg"></a>
						<h4><a href="#">玫瑰香葡萄</a></h4>
						<div class="prize">￥16.80</div>
					</li>
				</ul>
			</div>
		</div>

		<div class="r_wrap fr clearfix">
			<div class="sort_bar">
				<a href="#" class="active">默认</a>
				<a href="#">价格</a>
				<a href="#">人气</a>
			</div>

			<ul class="goods_type_list clearfix" id="LAY_ProductList">
				<li>

				</li>
			</ul>
			<div id="demo-laypage-all"></div>
		</div>
	</div>

	<div class="footer">
		<div class="foot_link">
			<a href="#">关于我们</a>
			<span>|</span>
			<a href="#">联系我们</a>
			<span>|</span>
			<a href="#">招聘人才</a>
			<span>|</span>
			<a href="#">友情链接</a>		
		</div>
		<p>CopyRight © 2024 北京鑫鑫科技有限公司 All Rights Reserved</p>
		<p>电话：010-8888888    京ICP备88888888号</p>
	</div>
	<script>
		var queryString = window.location.search;
		var urlParams = new URLSearchParams(queryString);
		var parentId = urlParams.get("parentId");
		var categoryId = urlParams.get("categoryId");
		var productQuery = {
			page: 1,
			limit: 10,
			name: null,
			categoryId: null,
			parentId: null
		};

		function getUrlParameter(name) {
			name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
			var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
			var results = regex.exec(location.search);
			return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
		}
		var searchKeyword = getUrlParameter('search');
		productQuery.name=searchKeyword;

		productQuery.parentId = parentId;
		productQuery.categoryId = categoryId;
		// 绑定搜索按钮点击事件
		$('#searchButton').click(function() {
			updateProductQuery(); // 更新 productQuery 对象
			productQuery.page=1;
			sendQuery(); // 发送查询请求
		});
		// 页面加载完成后自动执行一次查询
		$(document).ready(function() {
			sendQuery();
		});

		function updateProductQuery() {
			var searchText = $('#searchInput').val(); // 获取搜索框中的值
			productQuery.name = searchText || null; // 更新 productQuery 中的 model 字段
		}
		function sendQuery() {
			$.post(
					'/product/listPortal',
					productQuery, // 将 productQuery 对象作为数据发送
					function (result) {
						if (result.code == 0) {
							renderProductList(result);
							page(result.count);
							console.log(result.data);
							console.log(result.count);
							// 更新分页组件的总页数
						}
					},
					'json'
			);
		}


		function renderProductList(result) {
			console.log(productQuery)
			if (result.code == 0) {
				var html = '';
				$('#LAY_ProductList').empty();
				$(result.data).each(function () {
					html += '<li id="'+this.id+'">'
					html += '	<a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '"><img src="' + this.mainImage + '"></a>'
					html += '	<h4><a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '">' + this.name + '</a></h4>'
					html += '	<div class="operate">'
					html += '		<span class="prize">¥ ' + this.price + '</span>'
					html += '		<span class="unit">' + this.price + '/件</span>'
					html += '		<a href="javascript:;" class="add_goods" title="加入购物车" id="add_cart"></a>'
					html += '	</div>'
					html += '</li>'
				});
				$('#LAY_ProductList').append(html);

				//$('#add_cart').click(function () {
				$('#LAY_ProductList').on('click', '#add_cart', function () {
					//加入购物车之前首先判断有没有登录
					//如果没有登录首先完成登录
					//如果已经登录，就将商品信息插入到cart购物车表里面，然后跳转到购物车列表界面
					var productId = $(this).closest('li').attr('id');
					$.post(
							'/user/checkUserLogin',
							function (result) {
								if (result.code == 0) {
									//代表已经登录
									$.post(
											'/product/checkStock',
											{ 'id': productId },
											function (result) {
												if (result.code == 0) {
													//代表已经登录，直接插入购物车
													addToCart(productId);
												} else {
													mylayer.errorMsg(result.msg);
												}
											},
											'json'
									);
								} else {
									//没有登录
									addToCart(productId);
								}
							},
							'json'
					);
				});
				function addToCart(productId) {
					console.log('addToCart');
					$.ajax({
						url: '/cart/add?returnUri=/page/list?parentId='+parentId+'&categoryId='+categoryId+'',
						type: 'POST',
						data: {'productId': productId, 'quantity': 1},
						dataType: 'json',
						success: function (result) {
							if (result.code == 0) {
								mylayer.okMsg(result.msg);
							} else {
								mylayer.errorMsg(result.msg);
							}
						},
						complete : function(xhr, status) {
							//拦截器实现超时跳转到登录页面
							// 通过xhr取得响应头
							var REDIRECT = xhr.getResponseHeader("REDIRECT");
							//如果响应头中包含 REDIRECT 则说明是拦截器返回的需要重定向的请求
							if (REDIRECT == "REDIRECT") {
								var win = window;
								while (win != win.top) {
									win = win.top;
								}
								win.location.href = xhr.getResponseHeader("CONTEXTPATH");
							}
						}
					});
				}
			}
		}
		function page(count) {
			layui.use(function(){
				var laypage = layui.laypage;
				// 完整显示
				console.log(count)
				// 初始化分页
				laypage.render({
					elem: 'demo-laypage-all', // 元素 id
					count: count, // 假设总数据量
					curr: productQuery.page, // 设置当前页码
					limit:productQuery.limit,
					layout: ['count', 'prev', 'page', 'next', 'limit', 'refresh', 'skip'], // 功能布局
					jump: function(obj, first){
						if (!first) { // 首次不执行，避免重复触发
							productQuery.page = obj.curr; // 根据当前页码获取数据
							productQuery.limit = obj.limit;
							sendQuery();
						}
					}
				});
			});
		}


		//recommendedProducts
		$.post(
				'/user/checkUserLogin',
				function (result) {
					if (result.code == 0) {
						$.post(
								'/order/checkUserOrder',
								function (result) {
									if (result.data == 0) {
										//订单为0
										newProduct();
									} else {
										//智能推荐
										$.post(
												'/product/recommendedProducts',
												function (result) {
													if (result.code == 0) {
														var html = '';
														$('#newProduct').empty();
														$(result.data.slice(4, 7)).each(function () {
															html += '<li>'
															html += '	<a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '"><img src="' + this.mainImage + '"></a>'
															html += '	<h4><a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '">' + this.name + '</a></h4>'
															html += '	<div class="prize">¥ ' + this.price + '</div>'
															html += '</li>'
														});
														$('#newProduct').append(html);
													}
												},
												'json'
										);
									}
								},
								'json'
						);
					} else {
						//没有登录
						newProduct();
					}
				},
				'json'
		);

		function newProduct() {
			$.post(
					'/product/selectList',
					function (result) {
						if (result.code == 0) {
							var html = '';
							$('#newProduct').empty();
							$(result.data.slice(-2)).each(function () {
								html += '<li>'
								html += '	<a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '"><img src="' + this.mainImage + '"></a>'
								html += '	<h4><a href="/page/detail?productId=' + this.id + '&parentId=' + this.parentId + '&categoryId=' + this.categoryId + '">' + this.name + '</a></h4>'
								html += '	<div class="prize">¥ ' + this.price + '</div>'
								html += '</li>'
							});
							$('#newProduct').append(html);
						}
					},
					'json'
			);
		}

		if ((parentId == null || parentId === "") && (categoryId == null || categoryId === "")) {
			$('#categoryName').empty();
			$('#categoryName').append('<a href="/page/list">全部分类</a>');
		} else if (categoryId == null || categoryId === "") {
			$.post(
					'/category/parentName',
					{'parentId': parentId},
					function (result) {
						if (result.code == 0) {
							var html = '';
							$('#categoryName').empty();
							$(result.data).each(function () {
								html += '<a href="/page/list">全部分类</a>'
								html += '<span>></span>'
								html += '<a href="/page/list?parentId='+parentId+'">'+this.name+'</a>'
								$('#categoryName').append(html);
							})
						}
					},
					'json'
			);
		} else {
			$.post(
					'/category/categoryName',
					{'parentId': parentId, 'categoryId': categoryId},
					function (result) {
						if (result.code == 0) {
							var html = '';
							$('#categoryName').empty();
							html += '<a href="/page/list">全部分类</a>'
							html += '<span>></span>'
							html += '<a href="/page/list?parentId='+parentId+'">'+result.msg+'</a>'
							html += '<span>></span>'
							html += '<a href="/page/list?parentId='+parentId+'&categoryId='+categoryId+'">'+result.data+'</a>'
							$('#categoryName').append(html);

						}
					},
					'json'
			);
		}

		if (parentId == null || parentId === "") {
			$.post(
					'/category/listAll',
					function (result) {
						if (result.code == 0) {
							$('#LAY_CategoryList').empty();
							$(result.data).each(function () {
								$('#LAY_CategoryList').append('<li><a href="/page/list?parentId=' + this.id + '">'+this.name+'</a></li>');
							})
						}
					},
					'json'
			);
		} else {
			$.post(
					'/category/listChild',
					{'parentId': parentId },
					function (result) {
						if (result.code == 0) {
							$('#LAY_CategoryList').empty();
							$(result.data).each(function () {
								$('#LAY_CategoryList').append('<li><a href="/page/list?parentId=' + parentId + '&categoryId=' + this.id + '">'+this.name+'</a></li>');
							})
						}
					},
					'json'
			);
		}


		function logout() {
			layer.confirm(
					'您确认要退出么',
					{icon:3},
					function() {
						$.post(
								'/user/logout',
								function (result) {
									if (result.code == 0) {
										mylayer.okMsg(result.msg);
										setTimeout(function() {
											window.location.reload();
										}, 800);
									}
								},
								'json'
						);
						// location.href = '/admin?method=logout'
					}
			);
		}
	</script>
</body>
</html>